import request from "@/common/request/index.js";
import store from '@/store';
import base from '@/config/baseUrl';
import Vue from 'vue'

// import {router,RouterMount} from './../router'

let version_code = '';

let $http = new request({
	baseUrl: base.baseUrl,
	fileUrl: base.baseUrl,
	defaultUploadUrl: "/client/api/upload",
	header: {
		'Content-Type': 'application/json',
		'Accept': 'application/json',
	}
});

//请求开始拦截器
$http.requestStart = function(options) {
	
	console.log("请求开始", options);
	// 判断是否需要进行登录验证
	if (options && options.auth) {
		
		if (!store.state.AuthToken) {
			
			return "-1"
		}
	}
	let urlType = /^(http|https):\/\//.test(options.url);
	
	if (options.method == "FILE") {
		options.url = urlType ? options.url : this.fileUrl + options.url;
	} else {
		options.url = urlType ? options.url : this.baseUrl + options.url;
	}

	if (options.load) {
		store.commit("setLoadingShow", true);
	}

	
	if (options.method == "FILE" && options.maxSize) {
		let maxSize = options.maxSize;
		for (let item of options.files) {
			if (item.size > maxSize) {
				setTimeout(() => {
					uni.showToast({
						title: "图片过大，请重新上传",
						icon: "none"
					});
				}, 500);
				return false;
			}
		}
	}
	// #ifdef APP-PLUS

	if (version_code) {
		options.header['version_code'] = version_code;
	}
	// #endif
	
	if (store.state.AuthToken) {
		// options.header['Cookie'] = ('PHPSESSID=' + store.state.AuthToken).trim();
		
		// options.header['Cookie'] = ('PHPSESSID=' + store.state.AuthToken).trim();
		options.header['Cookie'] = ('PHPSESSID=' + uni.getStorageSync('AuthToken'));
	};
	// options.header['token'] ='eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTcwNzQsImV4cCI6bnVsbCwidXNlcl9uYW1lIjoiMmVkMmEwYjZhZTBiNDQzNDliOWFiN2RhZWIwOWY0ZWUiLCJqdGkiOm51bGwsImNsaWVudF9pZCI6ImFwaS1jbGllbnQiLCJzY29wZSI6WyJhbGwiXX0.CSl01wyS_t3DuAH19q4HwMlOau-k0iPw7IVjzbiPJTw2hkrjEV8Ce6T4-vTT0G-xQRUIDHTgpJAJVJ30OXt--92NJtGdPwceyZ8rjnKPs9yVIl45yyAlNPbMqjTJxlDhFEPbrR1e4fOnrFGV6IN6edet9ZWkzPkSrAv_njbSTgI';
	return options;
}

$http.requestEnd = function(options) {
	
	if (options.load) {
		
		store.commit("setLoadingShow", false);
	}
}
let loginPopupNum = 0;

$http.dataFactory = async function(res) {
	
	console.log("接口请求数据", {
		url: res.url,
		resolve: res.response,
		header: res.header,
		data: res.data,
		method: res.method,
	});
	
	if (res.response.statusCode && res.response.statusCode == 200) {

		let httpData = res.response.data;

		if (typeof(httpData) == "string") {
			httpData = JSON.parse(httpData);
		}
		if (httpData.result == 1) {
			return Promise.resolve(httpData);
		} else if (httpData.status == 401) {

			if (res.resend <= 2 && res.resend > 0) {
				// store.commit("userInfo", tokenResult);
				let result = await $http.request({
					url: res.url,
					data: res.data,
					method: res.method,
					header: res.header,
					isPrompt: res.isPrompt, 
					load: res.load, 
					isFactory: res.isFactory,
					resend: res.resend -= 1
				});
				// 返回正确的结果(then接受数据)
				return Promise.resolve(result);
			}
			store.commit("emptyUserInfo");
			if (loginPopupNum <= 0) {
				loginPopupNum++;
				uni.showModal({
					title: '温馨提示',
					content: "请登录用户",
					confirmText: "去登录",
					cancelText: "再逛会",
					success: function(res) {
						loginPopupNum--;
						if (res.confirm) {

						
						}
					}
				});
			}
			return Promise.reject({
				statusCode: 0,
				errMsg: "【request】" + (httpData.data || httpData.message),
				data: res.data
			});
		} else if (httpData.status == 311) {
			uni.showModal({
				title: '温馨提示',
				content: httpData.message,
				confirmText: '去新增',
				cancelText: "再逛会",
				success: function(res) {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/CollectionAddress/CollectionAddress'
						})
					}
				}
			});
		} else if (httpData.status == 500) {
			uni.showToast({
				title: httpData.message,
				icon: "none"
			});
			return Promise.reject({
				statusCode: httpData.status,
				errMsg: "【request】" + (httpData.message),
				data: res.data
			});
		} else if (httpData.status == 403) {
			
			uni.showModal({
				// title: "请先设置支付密码",
				content: "请先设置支付密码",
				success() {
					uni.navigateTo({
						url: "pages/prefile/resetSecondaryPassword/resetSecondaryPassword"
					})
				},
			})
		} else if (httpData.status == 2000) {
			return Promise.reject({
				statusCode: httpData.status,
				errMsg: "【request】" + (httpData.message),
				data: res.data
			});
		} else if(httpData.result === 400 && httpData.msg === '请登录'){
			console.log('需要静默授权');
			// store.state.showLoginTip = true
			// getwxCode()
		}else if(httpData.result === 0 && httpData.msg === '请登录'){
			console.log('需要静默授权');
			// store.state.showLoginTip = true
		}else if (httpData.result === 400){
			store.commit("LOGIN_TIP", true);
			
			return Promise.reject({
				statusCode: httpData.status,
				errMsg: "【request】" + (httpData.msg),
				data: res.data
			});
			// uni.setStorageSync('fromLogin', router);
		} else { //其他错误提示   
				
				uni.showToast({
					title: httpData.msg,
					icon: "none",
					duration: 3000
				});
			

			// 返回错误的结果(catch接受数据)
			return Promise.reject({
				statusCode: httpData.status,
				errMsg: httpData.msg,
				data: res.data
			});
		}

	

	} else if (res.response.statusCode == 403) {
		if (loginPopupNum <= 0) {
			loginPopupNum++;
			uni.showModal({
				title: '温馨提示',
				content: "登录过期~",
				confirmText: "去登录",
				cancelText: "再逛会",
				success: function(res) {
					loginPopupNum--;
					if (res.confirm) {
						uni.navigateTo({
							url: "/pages/security/login/login"
						})
					}
				}
			});
		}
	
	} else {

		// 返回错误的结果(catch接受数据)
		return Promise.reject({
			statusCode: res.response.statusCode,
			errMsg: "【request】数据工厂验证不通过",
			data: res.data
		});
	}
};
// 错误回调
$http.requestError = function(e) {
	// e.statusCode === 0 是参数效验错误抛出的
	if (e.statusCode === 0) {
		throw e;
	} else if (e.statusCode === 2000 || e.statusCode === 500) {
		console.log(e);
	} else if (e.statusCode === -1 && loginPopupNum <= 0) {
		loginPopupNum++;
		
	} else {
		console.log(e);
	}
}

// 获取微信code
function getwxCode(){
		let _this = this
		// #ifdef MP-WEIXIN
		uni.login({
			onlyAuthorize:true,
			success(res) {
				let code = res.code
				wx.getUserInfo({
					success: (_info)=>{
						authorizedLogin(code,_info)
					}
				})
			},
		})
		// #endif
	
}
// 静默授权
function  authorizedLogin(_code,_info){
	 Vue.prototype.myHttp({
		url:'/addons/yun_shop/api.php',
		data:{
			route : 'member.login.index',
			code : _code,
			info : JSON.stringify(_info),
			mid : '',
		}
	}).then(res=>{
		console.log(res);
		if(res.data.result==1){
			uni.setStorageSync('AuthToken',res.data.data.session)
			console.log('重新设置AuthToken成功');
			// let pages = getCurrentPages(); // 当前页面
			// let beforePage = pages[pages.length - 1]; //v
			//  uni.redirectTo({
			//                         url: '/' + beforePage.route,
			//                         complete(mes) {
			//                             console.log(mes)
			//                         },
			// 						fail(err) {
			// 							console.log(err);
			// 						},
			// 						success(res) {
			// 							console.log(res);
			// 						}
								
			//                     })
		}
	})
}

export default $http
